<template>
  <div id="userRegisterPage">
    <h2 class="title">用户注册</h2>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      :model="formState"
      name="basic"
      label-align="left"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      autocomplete="off"
      @finish="handleSubmit"
    >
      <a-form-item
        label="账号"
        name="username"
        :rules="[{ required: true, message: '请输入账号' }]"
      >
        <a-input v-model:value="formState.username" placeholder="请输入账号" />
      </a-form-item>

      <a-form-item
        label="职位"
        name="adminName"
        :rules="[{ required: true, message: '请输入职位' }]"
      >
        <a-input v-model:value="formState.adminName" placeholder="请输入职位" />
      </a-form-item>

      <a-form-item
        label="类型"
        name="roleType"
        :rules="[{ required: true, message: '请输入类型' }]"
      >
        <a-input v-model:value="formState.roleType" placeholder="请输入类型" />
      </a-form-item>

      <a-form-item
        label="密码"
        name="password"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 6, message: '密码不能小于 6 位' }
        ]"
      >
        <a-input-password
          v-model:value="formState.password"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item
        label="确定密码"
        name="checkPassword"
        :rules="[
          { required: true, message: '请输入确认密码' },
          { min: 6, message: '确认密码不能小于 6 位' }
        ]"
      >
        <a-input-password
          v-model:value="formState.checkPassword"
          placeholder="请输入确认密码"
        />
      </a-form-item>
      <a-form-item :wrapper-col="{ offset: 4, span: 20 }">
        <a-button type="primary" html-type="submit">注册</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { userRegister } from '@/api/user'
import { reactive } from 'vue'
import { useLoginUserStore } from '@/store/useLoginUserStore'
import { message } from 'ant-design-vue'
import router from '@/router'
const loginUserStore = useLoginUserStore()

interface FormState {
  username: string
  password: string
  checkPassword: string
  adminName: string
  roleType: string
}

const formState = reactive<FormState>({
  username: '',
  password: '',
  checkPassword: '',
  adminName: '',
  roleType: ''
})

// 提交表单
const handleSubmit = async (values: any) => {
  // 前端校验
  if (formState.password !== formState.checkPassword) {
    message.error('您输入的密码不一致，请重新输入')
  } else {
    const res = await userRegister(values)
    // 注册成功
    if (res.data.code === 200 && res.data.data) {
      await loginUserStore.fetchLoginUser()
      message.success('注册成功')
      router.push({
        path: '/user/login',
        replace: true
      })
    } else {
      message.error('注册失败')
    }
  }
}
</script>
<style>
.title {
  margin: 0 auto;
  text-align: center;
  margin-bottom: 16px;
}
</style>
